library(MASS)
library(tidyverse)
library(stargazer)

# Load primary analysis data
IndustryType<-read_csv("Data/Industry.csv")
NetworkData<-read_csv("Data/NetworkData.csv")
MergerAcquisitionData<-read_csv("Data/MergerAcquisitionData.csv")


# Load Plot specific data
MA_Only_Data<-read_csv("Data/MADataset.csv")
Brief_Only_Data<-read_csv("Data/BriefDataset.csv")


# Join Data Sets
CompleteDataSet<-left_join(MergerAcquisitionData,NetworkData, by=c('orgId','YearBins'))
CompleteDataSet<-left_join(CompleteDataSet,IndustryType,by='orgId')

# Create Industry Variables
CompleteDataSet$IndustryID<-as.factor(CompleteDataSet$IndustryID)
CompleteDataSet$Finance<-ifelse(CompleteDataSet$IndustryID=="Finance",1,0)
CompleteDataSet$Manufacturing<-ifelse(CompleteDataSet$IndustryID=="Manufacturing",1,0)
CompleteDataSet$Retail<-ifelse(CompleteDataSet$IndustryID=="Retail",1,0)

# Convert Strings to factors
CompleteDataSet$YearBins<-as.factor(CompleteDataSet$YearBins)
CompleteDataSet$orgId<-as.factor(CompleteDataSet$orgId)

# Create Lags of Mergers & Acquistions
CompleteDataSet<-CompleteDataSet%>%
  group_by(orgId)%>%
  mutate(lagMA2=lag(lagMA1))%>%
  mutate(lagMA3=lag(lagMA2))

# Create lags of total mergers, acquisitions and partial acquisitions
CompleteDataSet<-CompleteDataSet%>%
  group_by(orgId)%>%
  mutate(lagM=lag(TotalMergerBin),lagA=lag(TotalAcqBin),lagPA=lag(TotalPartAcqBin))

# Normalize Betweenness Score
CompleteDataSet$BTN <- (CompleteDataSet$BT - mean(CompleteDataSet$BT, na.rm=T)) / sd(CompleteDataSet$BT, na.rm=T)


# Set companies who start with solo submissions to minimum network values

# Value is non-zero due to normalization
Min_BTN = -0.2878953
Min_EC = 0
Min_HC = 0
Min_DG = 0
Min_CN =0


CompleteDataSet %>% 
  mutate(BTN =if_else(is.na(BTN) & issueNumber>0, Min_BTN, BTN),
         EC = if_else(is.na(EC) & issueNumber>0, Min_EC, EC),
         CN = if_else(is.na(CN) & issueNumber>0, Min_CN, CN),
         DG = if_else(is.na(DG) & issueNumber>0, Min_DG, DG),
         HC = if_else(is.na(HC) & issueNumber>0, Min_HC, HC)) -> CompleteDataSet



################################################
# Creates Table 1 in the main paper 
################################################

M3<-glm.nb(issueNumber~TotalMABin+lagMA1+YearBins+orgId,data=CompleteDataSet,control = glm.control(maxit = 100000))
M2<-lm(winRate~TotalMABin+lagMA1+YearBins+orgId,  data=CompleteDataSet)
M1<-glm.nb(TotalBriefBin~TotalMABin+lagMA1+YearBins+orgId,data=CompleteDataSet)
M4<-lm(EC~TotalMABin+lagMA1+YearBins+orgId,  data=CompleteDataSet)
M5<-lm(BTN~TotalMABin+lagMA1+YearBins+orgId,  data=CompleteDataSet)
M6<-glm.nb(DG~TotalMABin+lagMA1+YearBins+orgId,data=CompleteDataSet,control = glm.control(maxit = 100000))
M7<-lm(HC~TotalMABin+lagMA1+YearBins+orgId,  data=CompleteDataSet)

stargazer::stargazer(M1,M2,M3,M4,M5,M6,M7, 
                     star.cutoffs = c(0.05), 
                     model.names = FALSE,
                     single.row = F,
                     omit = c('Year','orgId'),
                     keep.stat = c('n','aic','adj.rsq'),
                     notes="$^{*}$p$<$0.05",
                     notes.append = F,
                     style = 'ajps',
                     covariate.labels = c('Num. M&As','Lag M&As','Constant'),
                     dep.var.labels=c( "Num. Briefs", "Win Rate", "Num. Issues", "Eigenvector Cent.","Betweenness","Degree","Harmonic Centr."),
                     add.lines = list(c('Year FE','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark'),
                                      c('Company FE','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark'),
                                      c('Court FE','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark','\\checkmark'),
                                      c('Model Type','NB','OLS','NB','OLS','OLS','NB','OLS')),
                     type='text')


################################################
# Create Figure 1 in the main paper
################################################


briefTopics<-Brief_Only_Data%>%group_by(topic)%>%tally()
iTypes<-IndustryType%>%group_by(IndustryID)%>%tally()

# Brief topic plot
p1<-ggplot()+
  geom_bar(data = briefTopics%>%filter(!(is.na(topic))), aes(y=n/sum(n),x=topic), stat = 'identity',fill='#3D5A6C',alpha=0.6, color='#3D5A6C')+
  labs(y='Proportion of Briefs\n',x="\nCase Issue Area\n")+
  theme_bw()+
  theme(axis.text = element_text(face = "bold", size = 16),
        axis.title = element_text(face = "bold", size = 20),)

# Industry area plot
p2<-ggplot()+
  geom_bar(data = iTypes, aes(y=n/sum(n),x=IndustryID), stat = 'identity',fill='#72A98F',alpha=0.6, color='#72A98F')+
  labs(y='Proportion of Companies\n',x="\nCompany Industry Area")+
  theme_bw()+
  theme(axis.text = element_text(face = 'bold',size=16),
        axis.title = element_text(face='bold',size=20),
        axis.text.x = element_text(size = 12))

# Figure 1 Plots:

# First Plot
p1
# Second Plot
p2



################################################
# Create Figure 2 in the main paper
################################################

# Helper function to format data
GenerateOverTimeData<-function(MAData,  BriefData, Start, End, binSize){
  # Set Year Bins
  YearCuts<-seq(End,Start, by=-binSize)
  YearLabels<-seq(1,length(YearCuts)-1)
  YearBins<-cut(as.integer(BriefData$opinionYear), breaks = YearCuts, labels = YearLabels, dig.lab = 5)
  BriefData$YearBins<-as.integer(YearBins)
  
  
  BinLabel<-cut(as.integer(BriefData$opinionYear), breaks = YearCuts, dig.lab = 5)
  BriefData$BinMin<-as.integer(substr(BinLabel,2,5))
  BriefData$BinMax<-as.integer(substr(BinLabel,7,10))
  
  
  MAYearBins<-cut(as.integer(MAData$Year), breaks = YearCuts, labels = YearLabels, dig.lab = 5)
  MAData$YearBins<-as.integer(MAYearBins)
  
  CompanyRates<-MAData%>%group_by(YearBins,companyName)%>%tally()%>%group_by(YearBins)%>%tally(name='numCompanies')
  MARates<-MAData%>%group_by(YearBins)%>%summarise(numMA=sum(MA_Number, na.rm=T))
  WinRates<-BriefData%>%group_by(YearBins)%>%summarise(briefWinRate=mean(briefWin, na.rm = T))
  BriefRates<-BriefData%>%group_by(YearBins)%>%tally(name='numBriefs')
  YearIndicators<-BriefData%>%select(YearBins,BinMin,BinMax)%>%distinct()
  output<-Reduce(function(...) left_join(...,by='YearBins'), list(MARates,WinRates,BriefRates,YearIndicators,CompanyRates))
  return(output)
}

plot_data<-GenerateOverTimeData(MA_Only_Data,Brief_Only_Data, 1938, 2012,5)

# Construct MA and Brief Averages
plot_data <- plot_data%>%mutate(newMA=numMA/numCompanies, newBriefs=numBriefs/numCompanies)

# A yearholder to use during plotting
yearHolder<-data.frame(Year=seq(1924,2012))
yearHolder<-left_join(yearHolder, Brief_Only_Data%>%group_by(opinionYear)%>%tally(), by=c("Year"='opinionYear'))%>%
  mutate(n=ifelse(is.na(n),0,n))%>%
  filter(Year>1946)



# Plotting Parameters
cf <- 10
shadingAlpha <- 0.0018
lineSize=1.15
textSize=3.5
lineSize2=0.25
lineType='dotdash'
lineAlpha=0.75

# Figure 2 plot
ggplot(plot_data) +
  geom_hline(yintercept = 0.5, linetype = "dashed", size = 0.25, alpha = 0.25) +
  geom_vline(xintercept = 1953, linetype = lineType, color = "#323031", size = lineSize2, alpha=lineAlpha) +
  geom_rect(aes(xmin = -Inf, xmax = 1953, ymin = -Inf, ymax = Inf), fill = "#2176AE", alpha = shadingAlpha) +
  geom_vline(xintercept = 1969, linetype = lineType, color = "#323031", size = lineSize2, alpha=lineAlpha) +
  geom_rect(aes(xmin = 1953, xmax = 1969, ymin = -Inf, ymax = Inf), fill = "#2B2D42", alpha = shadingAlpha) +
  geom_vline(xintercept = 1986, linetype = lineType, color = "#323031", size = lineSize2, alpha=lineAlpha) +
  geom_rect(aes(xmin = 1969, xmax = 1986, ymin = -Inf, ymax = Inf), fill = "#8D99AE", alpha = shadingAlpha) +
  geom_vline(xintercept = 2005, linetype = lineType, color = "#323031", size = lineSize2, alpha=lineAlpha) +
  geom_rect(aes(xmin = 1986, xmax = 2005, ymin = -Inf, ymax = Inf), fill = "#FBB13C", alpha = shadingAlpha) +
  geom_rect(aes(xmin = 2005, xmax = Inf, ymin = -Inf, ymax = Inf), fill = "#273C2C", alpha = shadingAlpha) +
  annotate("text", x = 1977.5, y = 0.82, label = "The Burger Court\n(1969–1986)",  size = 6, fontface='bold', color="#8D99AE", alpha =0.5) +
  annotate("text", x = 1960.5, y = 0.82, label = "The Warren Court\n(1953–1969)",  size = 6, fontface='bold', color="#8D99AE",alpha=0.5) +
  annotate("text", x = 1995.5, y = 0.82, label = "The Rehnquist Court\n(1986–2005)",  size = 6, fontface='bold', color="#8D99AE", alpha =0.5) +
  annotate("text", x = 2010.25, y = 0.82, label = "The Roberts Court\n(2005–Present)",  size = 5.85, fontface='bold', color="#8D99AE", alpha =0.5) +
  geom_col(data=yearHolder,  aes(x=Year, y=((n)*1/500)), alpha=0.25, color='#3d405b', fill='#3d405b', width=.9)+
  geom_line(aes(x = BinMax, y = briefWinRate, color = "Win Rate"), size = lineSize) +
  geom_line(aes(x = BinMax, y = newMA * 1 / cf, color = "M&A Rate"), size = lineSize) +
  geom_point(aes(x = BinMax, y = newMA * 1 / cf, color = "M&A Rate"), size = 3, shape=24,fill="white", stroke=1.1) +
  geom_point(aes(x = BinMax, y = briefWinRate, color = "Win Rate"), size = 3, shape=21,fill="white", stroke=1.1) +
  scale_y_continuous("Case Win Rate\n",
                     limits = c(0.0, 1),
                     sec.axis = sec_axis(~ . * cf / 1, name = "Number of M&A Per Company\n")
  ) +
  scale_color_manual(name = "", 
                     values = c("#ffb703", "#2a9d8f",'#3d405b'), 
                     labels = c('M&A Rate','Win Rate','Briefs Submitted'),
                     guide = guide_legend(override.aes = list(shape = c(24,21)) )) +
  xlim(1950,2012)+
  scale_x_continuous(name='Year',breaks=c(plot_data$BinMax))+
  theme_bw()+
  theme(axis.title = element_text(face="bold", size=18),
        axis.text = element_text(size = 16),
        legend.text = element_text(size = 18),
        legend.position = 'bottom')
